function noHelp(evt) {
	evt = setEvent(evt);

	if (evt.keyCode == 112) evt.preventDefault();
}

var nav;
var cAlert, cConfirm;
window.onload = function() {
    nav = getNavegador();

    listen(window, 'keydown', noHelp);
	listen(document, 'keydown', noHelp);
	document.onhelp = function() {
		return false;
	};

    /* cAlert y cConfirm */

    cAlert = get('alertCap');
	if (cAlert) {
		cAlert.show = function(say, opc) {
			var aSay = get('aSay');
			clearNode(aSay);
			var txt = document.createTextNode(say);
			aSay.appendChild(txt);

			if (typeof opc != 'undefined') {
				gtn(this, 'img')[0].src = 'imgs/error.png';
				gtn(this, 'span')[0].innerHTML = 'Error';
			}

			var sw = document.documentElement.clientWidth;
			var sh = document.documentElement.clientHeight;

			var w = this.offsetWidth;
			var h = this.offsetHeight;

			var lf = Math.round((sw - w) / 2);
			var tp = Math.round((sh - h) / 2);

			this.style.left = lf + 'px';
			this.style.top = tp + 'px';
			this.style.visibility = 'visible';
			//gtn(this, 'div')[1].style.width = (w - 14) + 'px';

			this.capTop = document.createElement('div');
			this.capTop.id = 'capATop';
			getBody().appendChild(this.capTop);
			goOnTop(this.capTop);

			this.style.zIndex = this.capTop.style.zIndex + 1;
		};

		cAlert.onclose = function() {

		};

		cAlert.close = function() {
			removeElement(this.capTop);
			cAlert.style.visibility = 'hidden';

			gtn(this, 'img')[0].src = 'imgs/notification.png';
			gtn(this, 'span')[0].innerHTML = 'Advertencia';

			this.onclose();
		};
	}

	cConfirm = get('confirmCap');

	if (cConfirm) {
		var butts = gtn(cConfirm, 'button');
		cConfirm.btnOK = butts[0];
		cConfirm.btnCancel = butts[1];
		cConfirm.show = function(say) {
			cConfirm.btnCancel.onclick = function() {
				cConfirm.close();
				cConfirm.onCancel();
			};

			cConfirm.btnOK.onclick = function() {
				cConfirm.close();
				cConfirm.onOK();
			};

			var cSay = get('cSay');
            cSay.innerHTML = say;

			var sw = document.documentElement.clientWidth;
			var sh = document.documentElement.clientHeight;

			var w = this.offsetWidth;
			var h = this.offsetHeight;

			var lf = Math.round((sw - w) / 2);
			var tp = Math.round((sh - h) / 2);

			this.style.left = lf + 'px';
			this.style.top = tp + 'px';
			this.style.visibility = 'visible';
			//gtn(this, 'div')[1].style.width = (w - 14) + 'px';

			this.capTop = document.createElement('div');
			this.capTop.id = 'capTop';
			this.capTop.className = 'floating';
			getBody().appendChild(this.capTop);
			goOnTop(this.capTop);
			this.style.zIndex = this.capTop.style.zIndex + 1;
		};

		cConfirm.close = function() {
			getBody().removeChild(this.capTop);
			cConfirm.style.visibility = 'hidden';
		};

		cConfirm.onCancel = function() {

		};
		cConfirm.onOK = function() {

		};
	}

    /* Fin de cAlert y cConfirm */

    /* Menú */

    var mens = gtn('navMenu', 'span');
    var nm = mens.length, m;

    for (m = 0; m < nm; m ++) {
        var men = mens[m];
        listen(men, 'click', showMenu);
        listen(men, 'mouseover', overMenu);
    }

    document.onclick = function(evt) {
		if (nav) evt = event;
		evt = setEvent(evt);
		
		var capMen = get('module' + curMen);
		if (evt.target.parentNode.id != 'navMenu' && curMen) {
			if (parseInt(curMen) > 0) {
				capMen.style.visibility = 'hidden';
				get('barTop').style.visibility = 'hidden';
				get('lineTop').style.visibility = 'hidden';
			}	
			get('menu' + curMen).removeAttribute('class');
			curMen = 0;
		}
	};

    /* Fin de Menú */

    /* Ventanas flotantes */
    document.onmousemove = function(evt) {
	    if (capFloat) {
	    	if (nav) evt = event;
	        evt = setEvent(evt);

	        var x = evt.clientX;
	        var y = evt.clientY;

	        var pLeft = parseInt(capFloat.style.left);
	        var hDir = (x - xi) - pLeft;

	        //get('divSay').innerHTML = hDir;

	        if (hDir < 0 && pLeft > 10 || hDir > 0 && pLeft + capFloat.offsetWidth + 10 < screen.width) capFloat.style.left = (x - xi) + 'px';
	        capFloat.style.top = (y - yi) + 'px';
	    }
    };
    document.onmouseup = function(evt) {
        if (nav) evt = event;
        leaveCap(evt);
    }
    /* Fin de Ventanas flotantes */
}

/* Menu */

var curMen = 0;

function showMenu(evt) {
	//alert(obj);
	evt = setEvent(evt);
	obj = evt.target;
    var modID = obj.id.substr(4);
    //alert(modID);
	if (modID != 'cs') obj.className = 'over';
	curMen = modID;

	if (parseInt(modID) > 0) {
		var cap = get('module' + modID);

		var pos = getPos(obj);

		var lf = pos.left; // + evt.scrollLeft;
		var tp = pos.top + obj.offsetHeight + evt.scrollTop; // + evt.scrollTop;

		cap.style.left = lf + 'px';
		cap.style.top = (tp + 3) + 'px';

		cap.style.visibility = 'visible';

		var capBT = get('barTop');
		capBT.style.width = (obj.offsetWidth - 2) + 'px';
		capBT.style.left = lf + 'px';
		capBT.style.top = tp + 'px';
		capBT.style.visibility = 'visible';

		var capLT = get('lineTop');
		capLT.style.width = (cap.offsetWidth - parseInt(capBT.style.width) - 1) + 'px';
		capLT.style.left = (lf + obj.offsetWidth - 1) + 'px';
		capLT.style.top = (tp + 3) + 'px';
		capLT.style.visibility = 'visible';
	}
}

function overMenu(evt) {
	if (curMen) {

		if (parseInt(curMen) > 0) get('module' + curMen).style.visibility = 'hidden';
		get('menu' + curMen).removeAttribute('class');
		get('barTop').style.visibility = 'hidden';
		get('lineTop').style.visibility = 'hidden';
		showMenu(evt);
	}
}
/* Fin de Menú */

/* Mostrar Programa */
function loading() {
    get('loa').className = 'show';
}

function loaStop() {
    get('loa').className = 'none';
}

function goOnTop(obj) {
    obj = getObj(obj);

    var objs = gtn(document, 'section');
    var no = objs.length;
    var z = 0;

    for (var b = 0; b < no; b ++) {
        var rObj = objs[b];

        if (rObj != obj) {
            if (rObj.style.zIndex) {
                zT = rObj.style.zIndex;
                if (zT > z) z = zT;
            }
        }
    }

    z ++;

    obj.style.zIndex = z;
}

function setCapShowing(obj, opc) {
	obj = getObj(obj);

    if (typeof opc == 'undefined') opc = 'center';

    if (opc == 'center') {
       var w = document.documentElement.clientWidth;
       var h = document.documentElement.clientHeight;

       var wi = obj.offsetWidth;
       var he = obj.offsetHeight;

       var lf = Math.round((w - wi) / 2);
       var tp = Math.round((h - he) / 2);
    }

    obj.style.left = lf + 'px';
    obj.style.top =  tp + 'px';

    //alert("w: " + w + ', h: ' + h + ', wi: ' + wi + ', he: ' + he);
}

function createFloating(id, title, content, icon) {
    var win = document.createElement('section');
    win.id = id;

    var estr =  '<h2 onmousedown="setFloating(event);">' +
                    '<span>' +
                        '<img src="imgs/icons/' + icon + '" />' + title +
                    '</span>' +
                    '<a href="JavaScript:;" class="butt-close" title="Cerrar" onclick="removeElement(this.parentNode.parentNode);"></a>' +
                    '<a href="JavaScript:;" class="butt-mm" title="Minimizar" onclick="minRestCap(this.parentNode.parentNode, this);"></a>' +
                '</h2>' +
                '<article>' +
                    '<div>' +
                        '<img src=\"imgs/information.png\" alt=\"Información\" />' +
                        '<span>Nuevo</span>' +
                    '</div>' +
                    '<dialog>' +
                        '<form name="frm'+id+'" onsubmit="return false">'+content+'</form>' +
                    '</dialog>' +
                '</article>';

    win.innerHTML = estr;
    getBody().appendChild(win);
    goOnTop(win);

    return win;
}

function loadJSCSS(prgID) {
    var js = document.createElement('script');
    js.id = 'js-' + prgID;
    js.type = 'text/javascript';
    js.src = 'forms/js/' + prgID + '.js?rnd=' + Math.random();

    getHead().appendChild(js);

    var css = document.createElement('link');
    css.id = 'css-' + prgID;
    css.type = "text/css";
    css.rel = "stylesheet";
    css.href = 'forms/css/' + prgID + '.css?rnd=' + Math.random();

    getHead().appendChild(css);
}

function unloadJSCSS(prgID) {
    removeElement('js-' + prgID);
    removeElement('css-' + prgID);
}

function loadTimer() {
    var ljs = null;
    var nfjs = 0;

    this.isLoaded = function(prgID) {
        ljs = window.setInterval('lt.isLoa(' + prgID + ')', 1);
    }
    this.isLoa = function(prgID) {
        //alert(typeof window['frmBegin' + prgID]);
        if (typeof window['frmBegin' + prgID] === 'function') {
            window.clearInterval(ljs);
            this.onloaded();
            nfjs = 0;
        } else {
            nfjs ++;

            if (nfjs == 100) {
                var ajax = new Ajax();
                ajax.URL = 'forms/' + prgID + '.jsp';
                ajax.execGET();
                ajax.onresponse = function() {
                    if (this.ajax.status != 200) {
                        window.clearInterval(ljs);
                        loaStop();
                        nfjs = 0;
                        cAlert.show('Este programa se encuentra en desarrollo', 1);
                    }
                };
            }
        }
    }

    this.onloaded = function() {

    }
}
function loadProgram(prgID, title, icon) {
    if (!get('js-' + prgID)) loadJSCSS(prgID);
    window['win' + prgID] = new mngWin(prgID, title, icon);
}

var lt = new loadTimer();
function showProgram(prgID, title, icon) {
    loadProgram(prgID, title, icon);
    loading();
   
    lt.onloaded = function() {
        window['frmBegin' + prgID]();
        window['win' + prgID].createWin();
    }
    lt.isLoaded(prgID);
    //ljs = window.setInterval('isLoaded(' + prgID + ')', 1);
}

function mngWin(prgID, title, icon) {
	var eles, firstEle = null;

    var cols = new Array();
    var tc = null;
    var cc = 0, dt = 1;

	this.data = new Object();

	this.createWin = function(parent, addPrms) {
		var ajx = new Ajax();
        ajx.URL = 'forms/' + prgID + '.jsp';
		ajx.parent = this;

		if (typeof addPrms == 'undefined') addPrms = '';

        ajx.execGET(addPrms);
		ajx.onresponse = function() {
            
			if (ajx.ajax.status == 200) {
				var win = 'win' + prgID;

				if (get(win)) cap = get(win);
				else cap = createFloating(win, title, this.response, icon);

                if (window.navigator.userAgent.indexOf('Chrome') != -1 && gtn(cap, 'input').length > 0) gtn(cap, 'dialog')[0].style.width = (gtn(cap, 'h2')[0].offsetWidth - 22) + 'px';
				this.parent.onload();

				var buts = gtn(win, 'button');
				var nb = buts.length, b;

				for (b = 0; b < nb; b ++) buts[b].type = 'button';

				eles = document['frmwin' + prgID].elements;
				var ne = eles.length, e;

				for (e = 0; e < ne; e ++) {
					var ele = eles[e];
					cls = ele.className;

					if (cls.indexOf('entero') != -1) {
						listen(ele, 'keydown', fixEntero);
						if (ele.maxLength && cls.indexOf('noFill') == -1) listen(ele, 'blur', fixZeros);
					}	else if (cls.indexOf('decimal') != -1) {
						listen(ele, 'keydown', decimales);
						listen(ele, 'blur', fixDecimales);
					}	else if (cls.indexOf('porcentaje') != -1) listen(ele, 'keydown', porcentaje);

					if (!(ele.tagName.toLowerCase() == 'button' || ele.tagName.toLowerCase() == 'textarea' || ele.type == 'hidden' || ele.readOnly || ele.disabled)) {
						if (!firstEle) firstEle = ele;

						for (var x = e + 1; x < ne; x ++) {
							var xEle = eles[x];
							if (!(xEle.tagName.toLowerCase() == 'button' || xEle.type == 'hidden' || xEle.readOnly || xEle.disabled)) {
								ele.alt = xEle.id;

								listen(ele, 'keyup', goNext);
								break;
							}
						}
					}
				}

				var tables = gtn(cap, 'table');
				var nt = tables.length, t;

				for (t = 0; t < nt; t ++) {
					
                    var table = tables[t];
                    var heads = table.tHead.rows[0].cells;
                    var nh = heads.length, h;

                    for (h = 0; h < nh - 1; h ++) {
                        var head = heads[h];

                        if (head.hasChildNodes() && head.firstChild.nodeValue) {
                            var hTxt = document.createTextNode(head.firstChild.nodeValue);
                            var hLnk = document.createElement('a');
                            hLnk.href = 'JavaScript:;';
                            hLnk.title = 'Ordenar por "' + head.firstChild.nodeValue + '"';
                            hLnk.setAttribute('onclick', 'sortTable(this, ' + h + ');');
                            hLnk.appendChild(hTxt);
                            head.replaceChild(hLnk, head.firstChild);
                        }
                    }

                    fillTable(table);
				}

                setCapShowing(cap, 'center');
				cap.style.visibility = 'visible';

				if (typeof parent != 'undefined')  var capDis = this.parent.winDisabled(cap, parent);

				if (firstEle) firstEle.focus();
                //alert(this.parent.onshow);

                cap.parent = this.parent;
                cap.onremove = function() {
                    this.parent.onremove();
                    if (typeof capDis != 'undefined') removeElement(capDis);
                } 

				this.parent.onshow();
			}	else alert('Este programa se encuentra en desarrollo');
			loaStop();
		};
	};

	this.onload = function() {
        
	};
	this.onshow = function() {
        
	};

	this.clearForm = function() {
		for (e = 0; e < eles.length; e ++) {
			var ele = eles[e];
			var tag = ele.tagName.toLowerCase();
			if (tag == 'input') {
				var type = ele.type.toLowerCase();

				if (type == 'text' || type == 'password' || type == 'hidden' || type == 'file') ele.value = '';
				else if (type == 'checkbox' || type == 'radio') ele.checked = false;
			}	else if (tag == 'select') {
				ele.selectedIndex = 0;
			}	else if (tag == 'textarea') ele.value = '';
		}
		firstEle.focus();
	};

	this.setFrmDisabled = function(val) {
		for (e = 0; e < eles.length; e ++) {
            var ele = eles[e];
            if (ele.className.indexOf('no-disabled') == -1) ele.disabled = val;
        }
	};

    function setAlert(objEle, col1, col2) {
        objEle = getObj(objEle);

        var t = 10;
        var d = 50;

        var red1 = hex2dec(col1.substr(0, 2));
        var green1 = hex2dec(col1.substr(2, 2));
        var blue1 = hex2dec(col1.substr(4, 2));

        var red2 = hex2dec(col2.substr(0, 2));
        var green2 = hex2dec(col2.substr(2, 2));
        var blue2 = hex2dec(col2.substr(4, 2));

        var dRed = (red2 - red1) / d;
        var dGreen = (green2 - green1) / d;
        var dBlue = (blue2 - blue1) / d;

        for (var c = 0; c < d; c ++) {
            cols[c] = dec2hex(red1 + dRed * c) + dec2hex(green1 + dGreen * c) + dec2hex(blue1 + dBlue * c);
        }
        window.clearInterval(tc);
        tc = window.setInterval(function() {setColor(objEle);}, t);
    }

    function setColor(objEle) {
        objEle.style.backgroundColor = '#' + cols[cc];
        //alert(cols[cc]);

        cc += dt;

        if (cc == cols.length - 1) dt = -1;
        if (dt == -1 && cc == 0) {
            window.clearInterval(tc);
            dt = 1;
        }
    }

	this.say = function(msg, opc) {
		var spnSay = gtn('win' + prgID, 'span')[1];
        spnSay.innerHTML = msg;

		if (opc == 'loading') {
			img = 'tloader.gif';
			spnSay.removeAttribute('class');
		}	else if (opc == 'error') {
			img = 'exclamation.png';
			spnSay.className = 'red';
			setAlert(spnSay.parentNode, 'ECECEC', 'FFFFB5');
		}	else if (!opc || icon == 'info') {
			img = 'information.png';
			spnSay.removeAttribute('class');
			setAlert(spnSay.parentNode, 'ECECEC', 'FFFFB5');
		}	else {
			img = 'information.png';
			spnSay.removeAttribute('class');
			setAlert(spnSay.parentNode, 'ECECEC', 'FFFFB5');
		}
		var ima = gtn('win' + prgID, 'img')[1];
		ima.src = 'imgs/' + img;
	};

	this.loaProgram = function(msg, nod) {
		if (typeof nod == 'undefined') this.setFrmDisabled(true);
		this.say(msg, 'loading');
	};

	this.stopLoading = function(msg, opc, nod) {
		if (typeof nod == 'undefined') this.setFrmDisabled(false);
		if (opc == 'loading') opc = '';
		this.say(msg, opc);
	};

	this.showPopup = function(idpp, inp, title, method, heaFields, fields, putFunc, putFields, nf, mParams) {
		showPopup(prgID, idpp, inp, title, method, heaFields, fields, putFunc, putFields, nf, mParams);
	};

    this.showReport = function(report, title, file, ops, ori, html) {
        if (typeof ops == 'undefined') ops = '';
        if (typeof html == 'undefined') html = '';
        if (typeof ori == 'undefined') ori = 0;

        var rParams = 'report='+report+'&title='+encodeURIComponent(title)+'&file='+file+'&orientacion='+ori+'&'+ops+'&html='+encodeURIComponent(html);
        //alert(rParams);
        var rptAjax = new Ajax();
        rptAjax.parent = this;
        this.loaProgram('Procesando ...');
        rptAjax.execPOST(rParams);
        rptAjax.onresponse = function() {
            if (this.response) {
                this.parent.stopLoading('Listo!');
                window.open('report.jsp?report=' + report + '&title=' + encodeURIComponent(title) + '&ops=' + ops + '&file='+file + '&rnd='+Math.random());
            } else this.parent.stopLoading('No se ha conseguido crear el Reporte', 'error');
        };
    }

	this.winDisabled = function winDisabled(cap, parent) {
		parent = getObj(parent);
		var capDis = document.createElement('section');
		capDis.className = 'win-disab';

		var prnPos = getPos(parent);
		capDis.style.left = prnPos.left + 'px';
		capDis.style.top = prnPos.top + 'px';
		capDis.style.width = parent.offsetWidth + 'px';
		capDis.style.height = parent.offsetHeight + 'px';
		capDis.style.zIndex = parseInt(parent.style.zIndex, 10) + 1;

		cap.style.zIndex = parseInt(parent.style.zIndex, 10) + 2;

		/*cap.onremove = function() {
			removeElement(capDis);
		};*/

		getBody().appendChild(capDis);
        return capDis;
	};

    this.close = function() {
        removeCap('win' + prgID);
    }
    
    this.onclose = function() {

    }

    this.onremove = function() {
        unloadJSCSS(prgID);
        window['win' + prgID] = null;

        this.onclose();
    }
}

function showPopup(prgID, idpp, inp, title, method, heaFields, fields, putFunc, putFields, nf, mParams) {
    var ajx = new Ajax();
    ajx.parent = this;

    heaFields = heaFields.replace(/, /g, ',');
    fields = fields.replace(/, /g, ',');
    putFields = putFields.replace(/, /g, ',');

    if (typeof mParams == 'undefined') mParams = '';

    var tSnd = 'getPopup='+idpp+'&title='+encodeURIComponent(title)+'&method='+method+'&mParams='+mParams+
               '&heaFields='+heaFields+'&fields='+fields+'&putFunc='+putFunc+'&putFields='+putFields+'&nf='+nf;
    //alert(tSnd);
    window['win' + prgID].loaProgram('Procesando ...');

    ajx.execPOST(tSnd);
    ajx.onresponse = function() {
        inp = getObj(inp);
        var cap;

        if (get(idpp)) cap = get(idpp);
        else {
            cap = document.createElement('section');
            cap.className = 'sct-popup';
            cap.id = idpp;

            var pos = getPos(inp);

            cap.style.left = (pos.left + inp.offsetWidth + 5) + 'px';
            cap.style.top = pos.top + 'px';

            getBody().appendChild(cap);
            cap.style.visibility = 'visible';
        }

        cap.innerHTML = this.response;

        var thsHead = gtn(cap, 'tr')[0].cells;
        var nt = thsHead.length, t;

        for (t = 0; t < nt; t ++) {
            var th = thsHead[t];
            th.style.width = (th.offsetWidth - 10) + 'px';
        }

        fillTable(gtn(cap, 'table')[0]);

        var capDis = window['win'+prgID].winDisabled(cap, 'win' + prgID);
        cap.onremove = function() {
            removeElement(capDis);
            inp.focus();
        }

        window['win' + prgID].stopLoading('Listo!');
        gtn(cap, 'input')[0].focus();
    };
}

function getNodeValue(node) {
    if (node.hasChildNodes()) {
        while (node.hasChildNodes()) {
            node = node.firstChild;
        }
        return node.nodeValue.trim();
    } else return '';
}

function searchInPopup(evt, idpp, nf) {
    evt = setEvent(evt);

    var table = get('tbl-'+idpp);
    var tBod = table.tBodies[0];
    
    var val = evt.target.value.toLowerCase();

    var trs = tBod.rows;
    var nt = trs.length, t;

    var dts = table.summary.split(',');
    var c = dts[0];
    var n = dts[1];

    var m = 0;
    for (t = 0; t < nt; t ++) {
        var tr = trs[t];
        var td = tr.cells[nf];
        var tdVal = getNodeValue(td);

        if (tdVal && tdVal.toLowerCase().indexOf(val) == -1) tr.className = 'none';
        else {
            tr.removeAttribute('class');
            m ++;
        }
    }

    var trHea = table.tHead.rows[0];

    var i, j;

    if (m <= n) {
        for (i = m; i < n; i ++) {
            tr = document.createElement('tr');

            for (j = 0; j < c; j ++) {
                td = document.createElement('td');
                td.innerHTML = '&nbsp;';

                tr.appendChild(td);
            }
            tBod.appendChild(tr);
        }

        if (trHea.cells.length > c) {
            trHea.deleteCell(c);
        }
    } else {
        var del = true, nr;
        while (del) {
            nr = tBod.rows.length;
            if (m > n) {
                var td0 = tBod.rows[nr - 1].cells[0];
                var tag = td0.firstChild.tagName ? true : false;

                if (!tag) {
                    tBod.deleteRow(nr - 1);
                    m --;
                } else del = false;
            } else del = false;
        }

        if (m > n) {
            if (trHea.cells.length == c) {
                var th = document.createElement('th');
                th.innerHTML = '&nbsp;';
                th.width = 6;
                if (table.tHead.rows.length > 1) th.rowSpan = table.tHead.rows.length;
                trHea.appendChild(th);
            }

            var hc = 21;
            //alert(hc);
            tBod.style.height = ((hc + 1) * n  - 1) + 'px';
        }
    }

    if (evt.keyCode == 13) {
        var func = gtn(tBod.rows[tBod.title], 'a')[0].onclick.toString();
        var pi = func.indexOf('{') + 1;
        var pf = func.indexOf(')', pi);

        func = func.substr(pi, pf - pi + 1).trim();
        eval(func);
    }

    if (evt.keyCode == 40 || evt.keyCode == 38) {
        var trSel = parseInt(tBod.title);
        var sTR = null;

        if (trSel > -1) gtn(tBod.rows[trSel], 'a')[0].removeAttribute('class');

        do {
            sTR = null;
            if (evt.keyCode == 40) trSel ++;
            else trSel --;

            if (trSel > -1 && trSel < tBod.rows.length) sTR = tBod.rows[trSel];
            if (typeof sTR == 'undefined' || sTR == null) break;
            if (gtn(sTR, 'a').length == 0) {
                trSel --;
                break;
            }
        }   while (!(trSel > - 1 && !sTR.className));

        if (trSel > -1) {
            gtn(tBod.rows[trSel], 'a')[0].className = 'over';
        }

        tBod.title = trSel;
    } else {
        if (tBod.title > -1) gtn(tBod.rows[tBod.title], 'a')[0].removeAttribute('class');
        tBod.title = '-1';
    }
}

function minRestCap(cap, lnk) {
	cap = getObj(cap);
	
	var tit = gtn(cap, 'h2')[0];
	var bod = gtn(cap, 'article')[0];
	
	if (bod.className == 'none') {
		bod.removeAttribute('class');
		lnk.className = 'butt-mm';
		lnk.title = 'Minimizar';
		tit.style.width = '100%';
		goOnTop(cap);
	}	else {
		bod.className = 'none';
		lnk.className = 'butt-rest';
		lnk.title = 'Restaurar';
		
		if (!nav) tit.style.width = 'auto';
	}
}

function goNext(evt) {
	evt = setEvent(evt);
	//alert(evt.target.rel);
	if (evt.keyCode == 13) get(evt.target.alt).focus();
}
/* Fin de Mostrar Programa */

/* Filtros */

function posCursor(obj) {
	obj = getObj(obj);

    var cursor = -1;

    if (document.selection && (document.selection != 'undefined')) {
         var _range = document.selection.createRange();
         var contador = 0;
         while (_range.move('character', -1)) contador ++;
         cursor = contador;
    } else if (obj.selectionStart >= 0) cursor = obj.selectionStart;

    return cursor;
}

function fixEntero(evt) {
    evt = setEvent(evt);

    if (evt.shiftKey) {
    	evt.preventDefault();
    	return false;
    }

    var key = evt.keyCode;

   // alert(key);
    if (!((key > 47 && key < 58) || (key > 95 && key < 106) || key == 8 || key == 9 || key == 13 || key == 35 || key == 36 || key == 37 || key == 39 || key == 46)) {
       evt.preventDefault();
    }
}

function decimales(evt) {
    evt = setEvent(evt);
    var cls = evt.target.className;

    var pi = cls.indexOf("decimal") + 7;
    var pf = cls.indexOf(" ", pi);

    if (pf != -1) n = cls.substr(pi, pf - pi);
    else n = cls.substr(pi);
    //alert(n);
    decimal(evt, n);
}

function decimal(evt, n) {
    evt = setEvent(evt);

    if (evt.shiftKey) {
    	evt.preventDefault();
    	return false;
    }

    var key = evt.keyCode;

    if ((key > 47 && key < 58) || (key > 95 && key < 106) || key == 8 || key == 9 || key == 13 || key == 35 || key == 36 || key == 37 || key == 39 || key == 46 || key == 110 || key == 190) {
       var obj = evt.target;
       var val = obj.value;

       var pp = val.indexOf(".");

       if (pp != -1) {
          if (key == 110 || key == 190) evt.preventDefault();

          if ((key > 47 && key < 58) || (key > 95 && key < 106)) {
             var pPos = posCursor(obj);

             if (pPos > pp && obj.selectionEnd - obj.selectionStart == 0) {
                var nDec = val.substr(pp + 1).length;
                if (nDec >= n) evt.preventDefault();
             }
          }
       }
    } else evt.preventDefault();
}

function fixDecimal(numero, n) {
	numero = parseFloat(numero);

	if (!isNaN(numero)) {
		numero = Math.round(numero * Math.pow(10, n)) / Math.pow(10, n);

		numero = String(numero);

		var pd = numero.indexOf('.');
		if (pd == -1) numero += '.';

		var dd = numero.split('.');
		var dec = dd[1];
		var nDec = dec.length;

		if (nDec < n) {
			for (var i = 0; i < n - nDec; i ++) dec += '0';
		}	else dec = dec.substr(0, n);

		return dd[0] + '.' + dec;
	}	else return '';
}

function fixDecimales(evt) {
	var obj = setEvent(evt).target;
	var cls = obj.className;
	var pi = cls.indexOf('decimal');
	var n = cls.substr(pi + 7, 1);

	obj.value = fixDecimal(obj.value, n);
}
function fixZeros(evt) {
	var obj = setEvent(evt).target;
	var val = obj.value;

	if (val) {
		var n = obj.maxLength;

		obj.value = fillZeros(val, n);
	}
}
function fillZeros(val, length) {
	var f = length - new String(val).length;

	for (var c = 0; c < f; c ++) val = "0" + val;

	return val;
}
function porcentaje(evt) {
     evt = setEvent(evt);

     var n = 2;

     var key = evt.keyCode;

     if ((key > 47 && key < 58) || (key > 95 && key < 106) || key == 8 || key == 9 || key == 13 || key == 35 || key == 36 || key == 37 || key == 39 || key == 46 || key == 110 || key == 190) {
        var obj = evt.target;
        var val = obj.value;

        var pp = val.indexOf('.');

        if ((key > 47 && key < 58) || (key > 95 && key < 106)) {

           var pPos = posCursor(obj);

           if (key > 47 && key < 58) chr = String.fromCharCode(key);
           else chr = String.fromCharCode(key - 48);

           var arrVal = val.split('');
           var nArr = arrVal.length;
           for (var i = nArr + 1; i > pPos; i --) {
               arrVal[i] = arrVal[i - 1];
           }
           arrVal[pPos] = chr;

           var tVal = arrVal.join('');
           if (parseFloat(tVal) >= 100) evt.preventDefault();

           if (pp != -1) {

              if (pPos > pp) {
                 var nDec = val.substr(pp + 1).length;
                 if (nDec >= n) evt.preventDefault();
              }
           }
        } else if ((key == 110 || key == 190) && pp != -1) {
           evt.preventDefault();
        }

     } else evt.preventDefault();

}

/* Fin de Filtros */

/* Tablas */

function orderTable(a, b, h, ord) {
    var aCell = a.cells[h];
    var bCell = b.cells[h];
    
	var fieldA = aCell.hasChildNodes() ? aCell.firstChild.nodeValue.trim() : '';
	var fieldB = bCell.hasChildNodes() ? bCell.firstChild.nodeValue.trim() : '';

    if (fieldB == '') return -1;
    else {
        if (ord == 'order') return fieldA.localeCompare(fieldB);
        else if (ord == 'rorder') return fieldB.localeCompare(fieldA);
        else return null;
    }
}

function sortTable(lnk, h) {
	var head = lnk.parentNode.parentNode.parentNode;
	var table = head.parentNode;

	var tBody = table.tBodies[0];
	var trs = tBody.rows;
	var nt = trs.length, t;

	var th = lnk.parentNode;
	var order = (th.className == 'order') ? 'rorder' : 'order';

	var rows = Array.prototype.slice.call(trs);

	rows.sort(function(a, b) {return orderTable(a, b, h, order);});

	for (t = nt - 1; t >= 0; t --) {
		tBody.deleteRow(t);
	}

	for (t = 0; t < nt; t ++) {
		tBody.appendChild(rows[t]);
	}

	if (head.className) {
		var hp = head.className.split('-')[1];
		head.rows[0].cells[hp].className = '';
	}

	th.className = order;

	head.className = 'o-' + h;
}

function fillTable(table, rows) {
    table = getObj(table);

    var dats = table.summary.split(',');
    
    var c = dats[0];
    var n = dats[1];

    var rHea = table.tHead.rows[0];
    var tHeads = rHea.cells;
	var tBod = table.tBodies[0];
    if (typeof rows != 'undefined') tBod.innerHTML = rows;

	var m = tBod.rows.length, i, j;
    var nc = tHeads.length;

    if (m <= n) {
        for (i = m; i < n; i ++) {
            var tr = document.createElement('tr');

            for (j = 0; j < c; j ++) {
                var td = document.createElement('td');
                if (tHeads[j].colSpan > 1) td.colSpan = tHeads[j].colSpan;
                td.innerHTML = '&nbsp;';

                tr.appendChild(td);
            }

            tBod.appendChild(tr);
        }
        if (nc > c) {
            rHea.deleteCell(c);
        }

        tBod.removeAttribute('style');
    } else {
        if (nc == c) {
            var th = document.createElement('th');
            th.innerHTML = '&nbsp;';
            th.width = 6;
            if (table.tHead.rows.length > 1) th.rowSpan = table.tHead.rows.length;
            rHea.appendChild(th);
        }

        var hc = tBod.rows[0].cells[0].offsetHeight;
        //alert(hc);
        tBod.style.height = ((hc + 1) * n  - 1) + 'px';
    }
}

/* Fin de Tablas */

/* Efecto de Alerta */

function dec2hex(dec) {
	var hexs = '0123456789ABCDEF';
	var low = dec % 16;
	var high = (dec - low)/16;
	hex = '' + hexs.charAt(high) + hexs.charAt(low);

	return hex;
}

function hex2dec(hex) {
	return parseInt(hex, 16);
}

/* Fin de Efecto de alert */

/* Ventanas flotantes */

var capFloat = null;
var xi = 0;
var yi = 0;

function setFloating(evt) {
	evt = setEvent(evt);

    var objTit = evt.target;
	if (objTit.tagName.toLowerCase() == 'h2') {
	    capFloat = objTit.parentNode;
        //alert(capFloat);

	    xi = evt.clientX;
	    yi = evt.clientY;

	    if (capFloat.style.left) xi -= parseInt(capFloat.style.left);
	    if (capFloat.style.top) yi -= parseInt(capFloat.style.top);

        objTit.className = 'moving';
	    goOnTop(capFloat);
	}
}

function leaveCap(evt) {
	evt = setEvent(evt);

    var win = evt.target;

	if (typeof win.onmousedown != 'undefined' && win.onmousedown.toString().indexOf('onmousedown') != -1) {
        win.removeAttribute('class');
    }
    capFloat = null;
}

/* Fin de Ventanas flotantes */
